<template>
  <common-list>
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增
        </el-button>
      </el-col>
    </el-row>

    <common-table slot="content" v-loading="loading" :data="settingList">
      <el-table-column
        label="邮件服务器名称"
        align="left"
        prop="emailServerName"
        show-overflow-tooltip
      />
      <el-table-column
        label="邮件服务器编码"
        align="left"
        prop="emailServerCode"
        show-overflow-tooltip
      />
      <el-table-column
        label="邮箱地址"
        align="left"
        prop="address"
        show-overflow-tooltip
      />
      <el-table-column
        label="显示名称"
        align="left"
        prop="showName"
        show-overflow-tooltip
      />
      <el-table-column
        label="发件服务器地址"
        align="left"
        prop="sendingIp"
        show-overflow-tooltip
      />
      <el-table-column label="端口号" align="left" prop="port" width="80px" />
      <el-table-column label="状态" align="center" prop="state" width="80px">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.state === 1">停用</el-tag>
          <el-tag type="success" v-if="scope.row.state === 0">启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="160px">
        <template slot-scope="scope">
          <el-button type="text" @click="getInfo(scope.row)"> 详情 </el-button>
          <el-button type="text" @click="handleUpdate(scope.row)"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
            >{{ scope.row.state === 0 ? "停用" : "启用" }}
          </el-button>
          <el-button type="text" @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :button-loading="isPersistenceLoading"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="18">
          <el-col :span="12">
            <el-form-item label="邮件服务器名称" prop="emailServerName">
              <common-input
                v-model="form.emailServerName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="address">
              <common-input
                :verify="false"
                v-model="form.address"
                placeholder="例：test@123.com"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="18">
          <el-col :span="12">
            <el-form-item label="显示名称" prop="showName">
              <common-input v-model="form.showName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <common-input
                :verify="false"
                v-model="form.password"
                placeholder="********"
                type="password"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="18">
          <el-col :span="12">
            <el-form-item label="发件服务器地址" prop="sendingIp">
              <common-input
                :verify="false"
                v-model="form.sendingIp"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口号" prop="port">
              <common-input-number
                :max-length="5"
                v-model="form.port"
              ></common-input-number>
              <!--              <common-input v-model="form.port" placeholder="请输入" />-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="18">
          <el-col :span="12">
            <el-form-item label="是否是SSL加密" prop="sslFlag">
              <el-radio-group v-model="form.sslFlag">
                <el-radio :label="1">否</el-radio>
                <el-radio :label="0">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="测试收件邮箱"
              prop="receiverAddress"
              :rules="isTest ? rules.receiverAddress : []"
            >
              <common-input
                :verify="false"
                v-model="form.receiverAddress"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12" v-show="form.id">-->
          <!--            <el-form-item label="状态" prop="state">-->
          <!--              <el-radio-group v-model="form.state">-->
          <!--                <el-radio :label="1">停用</el-radio>-->
          <!--                <el-radio :label="0">启用</el-radio>-->
          <!--              </el-radio-group>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
      <common-interval-button
        ref="intervalButton"
        slot="footer-button"
        :interval="10"
        @click="testEmailMessage"
        :isDisabled="isDisabled"
      >
        邮件测试
      </common-interval-button>
    </common-edit-dialog>
    <common-info-dialog
      :visible="openInfo"
      :title="detailsTitle"
      :infoLoading="infoLoading"
      @cancel="cancelInfo"
    >
      <common-info-table>
        <common-info-table-cell label="邮件服务器名称">{{
          form.emailServerName
        }}</common-info-table-cell>
        <common-info-table-cell label="邮件服务器编码">{{
          form.emailServerCode
        }}</common-info-table-cell>
        <common-info-table-cell label="邮箱地址">{{
          form.address
        }}</common-info-table-cell>
        <common-info-table-cell label="显示名称">{{
          form.showName
        }}</common-info-table-cell>
        <common-info-table-cell label="发件服务器地址">{{
          form.sendingIp
        }}</common-info-table-cell>
        <common-info-table-cell label="端口号">{{
          form.port
        }}</common-info-table-cell>
        <common-info-table-cell label="状态">{{
          form.state === 0 ? "启用" : "停用"
        }}</common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import {
  listSetting,
  getSetting,
  delSetting,
  addSetting,
  updateSetting,
  setEmailStatus,
  testSendEmailMessage,
  queryActiveCount,
} from "@/api/system/emailsetting";
import Template from "./template.vue";
import { portRule, emailRule } from "@/utils/formRules";
import { validateIPAndURL } from "@/utils/formValidates";
import { encode } from "@/utils/aesUtils";
import { deepClone } from "../../../utils";
import BaseList from "@/mixins/BaseList";

export default {
  name: "Setting",
  mixins: [BaseList],
  components: {
    Template,
  },
  data() {
    return {
      detailsTitle: "", //详情标题
      openInfo: false, //详情弹框
      isPersistenceLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      settingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        sslFlag: 1,
        id: null,
        emailServerName: null,
        emailServerCode: null,
        address: null,
        password: null,
        showName: null,
        sendingIp: null,
        port: 80,
        state: 1,
        isDefault: null,
        createUserCode: null,
        remark: null,
        receiverAddress: null,
      },
      type: "ip", // ip url
      testForm: {},
      testOpen: false,
      // 表单校验
      rules: {
        emailServerName: [
          {
            required: true,
            message: "请输入邮件服务器名称",
            trigger: "blur",
          },
        ],
        emailServerCode: [
          {
            required: true,
            message: "请输入邮件服务器编码",
            trigger: "blur",
          },
        ],
        address: emailRule,
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        showName: [
          { required: true, message: "请输入显示名称", trigger: "blur" },
        ],
        sendingIp: [
          { required: true, message: "请输入发件服务器地址", trigger: "blur" },
          // { required: true, validator: validateIPAndURL, trigger: 'blur', message: "发件服务器地址错误，支持IPV4/IPV6/URL格式"}
        ],
        port: portRule,
        state: [{ required: true, message: "请选择", trigger: "blur" }],
        receiverAddress: emailRule,
      },
      testRules: {
        emailAddress: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
        ],
        subject: [
          { required: true, message: "请输入邮件主题", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入邮件内容", trigger: "blur" },
        ],
      },
      isTest: false,
      isDisabled: false,
      infoLoading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //详情取消
    cancelInfo() {
      this.openInfo = false;
    },
    //详情
    getInfo(id) {
      this.detailsTitle = "邮件配置详情";
      this.openInfo = true;
      this.getSetting(id);
    },
    getSetting(id) {
      this.infoLoading = true;
      getSetting(id).then((res) => {
        if (res && (res.rescode === 200 || res.code === 200)) {
          this.form.emailServerName = res.data.dataList[0].emailServerName;
          this.form.emailServerCode = res.data.dataList[0].emailServerCode;
          this.form.address = res.data.dataList[0].address;
          this.form.showName = res.data.dataList[0].showName;
          this.form.sendingIp = res.data.dataList[0].sendingIp;
          this.form.port = res.data.dataList[0].port;
          this.form.state = res.data.dataList[0].state;
          this.infoLoading = false;
        } else {
          this.$GlobalErrorConfirm("获取信息失败", res.msg, "重新加载").then(
            () => {
              this.getSetting(id);
            }
          );
        }
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listSetting(this.queryParams)
        .then((res) => {
          if (res && (res.rescode === 200 || res.code === 200)) {
            this.settingList = res.data.dataList.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
              });
              return r;
            }, []);
            this.total = res.data.totalCount;
          } else {
            this.settingList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        if (row.state === 0) {
          const params = {
            id: row.id,
            state: row.state === 0 ? 1 : 0,
          };
          this.$GlobalDeleteConfirm(
            "停止后将影响二次登录，告警处理及时性，请确认是否停用"
          )
            .then(() => {
              setEmailStatus(params)
                .then((response) => {
                  if (
                    response &&
                    (response.code === 200 || response.rescode === 200)
                  ) {
                    this.$GlobalSuccessMessage("操作成功");
                    this.getList();
                    resolve(response);
                  } else {
                    reject();
                    this.$GlobalErrorConfirm("操作失败", response.msg).then();
                  }
                })
                .catch(() => reject());
            })
            .catch(() => {});
        } else {
          queryActiveCount()
            .then((res) => {
              if (res && res.data > 0) {
                return this.$GlobalErrorConfirm(
                  "操作失败",
                  "不能同时启动多台邮件服务器，请先停用其他的邮件服务器"
                );
              } else if (res && res.data === 0) {
                const params = {
                  id: row.id,
                  state: row.state === 0 ? 1 : 0,
                };
                setEmailStatus(params)
                  .then((response) => {
                    if (
                      response &&
                      (response.code === 200 || response.rescode === 200)
                    ) {
                      this.$GlobalSuccessMessage("操作成功");
                      this.getList();
                      resolve(response);
                    } else {
                      this.$GlobalErrorConfirm("操作失败", response.msg).then();
                    }
                  })
                  .catch(() => reject());
              }
            })
            .finally(() => {
              resolve();
            });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      console.log("====> ", this.$refs.form);
      this.$refs.form.resetFields();
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "新增邮件配置";
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      if (row.state === 0) {
        return this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      }
      const id = row.id || this.ids;
      getSetting({ id }).then((res) => {
        if (res && (res.code === 200 || res.rescode === 200)) {
          if (
            res.data.dataList &&
            res.data.dataList instanceof Array &&
            res.data.dataList.length !== 0
          ) {
            Reflect.ownKeys(this.form).forEach(
              (k) => (this.form[k] = res.data.dataList[0][k])
            );
            this.form.port = parseInt(this.form.port);
            this.open = true;
            this.title = "编辑邮件配置";
          }
        } else {
          this.$GlobalErrorConfirm("编辑失败", res.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.isTest = false;
      this.$nextTick(() => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              if (this.form.createTime) delete this.form.createTime;
              if (this.form.state === 0) {
                this.isPersistenceLoading = true;
                queryActiveCount()
                  .then((res) => {
                    if (res && res.data > 0) {
                      return this.$GlobalErrorConfirm(
                        "编辑失败",
                        "不能同时启动多台邮件服务器"
                      );
                    } else if (res && res.data === 0) {
                      this.updateData();
                    }
                  })
                  .finally(() => {
                    this.isPersistenceLoading = false;
                  });
              } else {
                this.updateData();
              }
            } else {
              if (!this.isPersistenceLoading) {
                this.isPersistenceLoading = true;
                addSetting({
                  ...this.form,
                  emailServerCode: "utf-8" + new Date().getTime(),
                })
                  .then((response) => {
                    if (
                      response &&
                      (response.code === 200 || response.rescode === 200)
                    ) {
                      this.$GlobalSuccessMessage("新增成功");
                      this.getList();
                      this.cancel();
                    } else {
                      this.$GlobalErrorConfirm(response.msg);
                    }
                  })
                  .finally(() => {
                    this.isPersistenceLoading = false;
                  });
              }
            }
          }
        });
      });
    },
    testEmailMessage() {
      this.isTest = true;
      this.isDisabled = true;
      this.$nextTick(() => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.$refs.intervalButton.start();
            if (this.form.createTime) delete this.form.createTime;
            let params = deepClone(this.form);
            params.receiverAddress = encode(this.form.receiverAddress);
            testSendEmailMessage(params)
              .then((response) => {
                if (
                  response &&
                  (response.code === 200 || response.rescode === 200)
                ) {
                  this.$GlobalSuccessMessage("测试成功");
                } else {
                  this.$GlobalErrorConfirm("测试失败", response.msg);
                }
              })
              .finally(() => (this.isDisabled = false));
          }
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.state === 0) {
        return this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
      }
      const id = row.id || this.ids;

      this.$GlobalDeleteConfirm()
        .then(() => {
          delSetting({ id }).then((response) => {
            if (
              response &&
              (response.code === 200 || response.rescode === 200)
            ) {
              this.getList();
              this.$GlobalSuccessMessage("删除成功");
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**
     * 更新
     */
    updateData() {
      if (this.isPersistenceLoading !== true) {
        this.isPersistenceLoading = true;
        updateSetting({
          ...this.form,
          emailServerCode: "utf-8" + new Date().getTime(),
        })
          .then((response) => {
            if (
              response &&
              (response.code === 200 || response.rescode === 200)
            ) {
              this.$GlobalSuccessMessage("编辑成功");
              this.getList();
              this.cancel();
            } else {
              this.$GlobalErrorConfirm("编辑失败", response.msg);
            }
          })
          .finally(() => {
            this.isPersistenceLoading = false;
          });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.emailSetting {
  .openState {
    color: #52c41a;
    background: #f6ffed;
    padding: 3px 7px;
    font-size: 12px;
    border-radius: 4px;
    border: 1px solid #b7eb8f;
  }

  .openState.stop {
    color: #f5222d;
    background: #fff1f0;
    border-color: #ffa39e;
  }
}
</style>
